package com.sk.waste.app.views;

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.WindowManager
import android.widget.Button
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.LinearLayout.LayoutParams
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lc.smc.lib.interfaces.LCInterface
import com.lc.smc.lib.utils.LCBaseUtil
import com.lc.smc.lib.utils.LCSPUtil
import com.sk.pay.lib.PayConfig
import com.sk.pay.lib.PaymentUtil
import com.sk.pay.lib.aipay.PayResult
import com.sk.waste.app.R
import com.sk.waste.app.adapters.DistrictAdapter
import com.sk.waste.app.application.MyApplication
import com.sk.waste.app.config.AppConfig
import com.sk.waste.app.config.NetWorkConfig
import com.sk.waste.app.models.TypeModel
import com.sk.waste.app.utils.BaseUtil
import com.sk.waste.app.utils.LcProgressUtil
import com.sk.waste.app.utils.OkHttpUtil
import okhttp3.Call
import org.json.JSONObject
import java.io.IOException


/**
 *  @time 2025/5/14  9:07
 *  @desc 支付
 */
class PaymentWindow() : PopupWindow(), OnClickListener {

    private lateinit var mContext: Activity
    private lateinit var mMenuView: View
    private lateinit var bttCancle: ImageButton
    private lateinit var ttvPrive: TextView
    private lateinit var ttvType: TextView
    private lateinit var checkboxAli: CheckBox
    private lateinit var layoutAliPay: LinearLayout
    private lateinit var checkboxWechat: CheckBox
    private lateinit var lyWechatPay: LinearLayout
    private lateinit var bttSubmit: Button

    var progressDialog: LcProgressUtil? = null
    private lateinit var callBackListener: LCInterface.LcCallBack
    val paymentUtil = PaymentUtil()

    fun init(context: Activity) {
        this.mContext = context
        findView()
        initPopu()
    }

    //初始化
    private fun initPopu() {
        this.contentView = mMenuView
        this.width = LayoutParams.MATCH_PARENT
        this.height = LayoutParams.WRAP_CONTENT
        //设置SelectPicPopupWindow弹出窗体可点击
        this.isFocusable = false
        this.softInputMode = WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
        this.isOutsideTouchable = false
        this.isTouchable = true
        this.isClippingEnabled = false ///覆盖状态栏，
        setTouchInterceptor { view, motionEvent -> false }
    }

    @SuppressLint("NewApi")
    private fun findView() {
        val inflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        mMenuView = inflater.inflate(R.layout.view_payment_popuwindow, null)
        bttCancle = mMenuView.findViewById(R.id.view_payment_cancle)
        ttvPrive = mMenuView.findViewById(R.id.view_payment_title)
        ttvType = mMenuView.findViewById(R.id.view_payment_type)
        checkboxAli = mMenuView.findViewById(R.id.view_payment_ali_checkbox)
        layoutAliPay = mMenuView.findViewById(R.id.view_payment_ali_layout)
        checkboxWechat = mMenuView.findViewById(R.id.view_payment_wechat_checkbox)
        lyWechatPay = mMenuView.findViewById(R.id.view_payment_wechat_layout)
        bttSubmit = mMenuView.findViewById(R.id.view_payment_submit)

        bttCancle.setOnClickListener {
            dismiss()
        }

        layoutAliPay.setOnClickListener {
            checkboxAli.isChecked = true
            checkboxWechat.isChecked = false
        }

        lyWechatPay.setOnClickListener {
            checkboxAli.isChecked = false
            checkboxWechat.isChecked = true
        }

        bttSubmit.setOnClickListener {
            if (checkboxAli.isChecked) {
                callBackListener.callBack("0")
            }
            if (checkboxWechat.isChecked) {
                callBackListener.callBack("1")
            }
            dismiss()
        }
    }


    override fun onClick(view: View?) {
        when (view?.id) {
            //地形
//            R.id.view_maplayer_terrain -> {
//                callBackListener.callBack("layout_terrain")
//            }
        }
    }


    fun showAtLocation(parent: View?, gravity: Int, x: Int, y: Int, price: String, type: String) {
        setBackgroundAlpha(0.8f)
        ttvPrive.text = "￥ "+price
        ttvType.text = type
        super.showAtLocation(parent, gravity, x, y)
    }

    /**
     *  @time 2024/7/8  16:39
     *  @author Im_jingwei
     *  @desc 事件回调接口
     */
    fun setPopuOnclickListener(listener: LCInterface.LcCallBack) {
        this.callBackListener = listener
    }


    /***************************  支付宝 start  *************************/
    /**
     *  @time 2024/5/7  11:29
     *  @desc 创建支付宝订单
     *  @param url
     */
    fun creatAliPay(paytype:String) {
        showProgress("正在创建支付订单...")
        val httpUtil = OkHttpUtil()
        val jsonObject = JSONObject()
        jsonObject.put("productId", paytype)
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_ALIPAY_CREATE
        httpUtil.httpRequest(url, token, jsonObject.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                LCBaseUtil.showToast(mContext, "支付宝创建订单失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    val jsonObject = JSONObject(response)
                    val code = jsonObject.getInt("code")
                    val order = jsonObject.getString("data")
                    val msg = jsonObject.getString("message")
                    if (code == 200) {
                        toAlipayMent(order)
                    } else {
                        LCBaseUtil.showToast(mContext, "支付宝创建订单异常，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "支付宝创建订单失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2025/8/7  20:00
     *  @author Im_jingwei
     *  @desc 调用支付宝支付
     */
    fun toAlipayMent(orderInfo: String) {
//                val testJson = JSONObject()
//                testJson.put("appid","wxd930ea5d5a258f4f")
//                testJson.put("partnerid","1900000109")
//                testJson.put("prepayid","1101000000140415649af9fc314aa427")
//                testJson.put("packages","Sign=WXPay")
//                testJson.put("noncestr","1101000000140429eb40476f8896f4c9")
//                testJson.put("timestamp","1398746574")
//                testJson.put("sign","oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ\\/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGuT+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feLOQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq\\/xDg==\";")
//                paymentUtil.wechatPay(mContext,testJson)

//        val info = "app_id=2015052600090779&biz_content=%7B%22timeout_express%22%3A%2230m%22%2C%22seller_id%22%3A%22%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.02%22%2C%22subject%22%3A%221%22%2C%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22314VYGIAGG7ZOYY%22%7D&charset=utf-8&method=alipay.trade.app.pay&sign_type=RSA2&timestamp=2016-08-15%2012%3A12%3A15&version=1.0&sign=MsbylYkCzlfYLy9PeRwUUIg9nZPeN9SfXPNavUCroGKR5Kqvx0nEnd3eRmKxJuthNUx4ERCXe552EV9PfwexqW%2B1wbKOdYtDIb4%2B7PL3Pc94RZL0zKaWcaY3tSL89%2FuAVUsQuFqEJdhIukuKygrXucvejOUgTCfoUdwTi7z%2BZzQ%3D"
        paymentUtil.aliPay(mContext, orderInfo, mHandler)

    }

    private val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                PayConfig.ALIPAY_SDK_PAY_FLAG -> {
                    val payResult = PayResult(msg.obj as Map<String?, String?>)
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    val resultInfo = payResult.result // 同步返回需要验证的信息
                    val resultStatus = payResult.resultStatus
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        PayDemoActivity.showAlert(this@PayDemoActivity, getString(R.string.pay_success) + payResult)
//                        verifyAliPay()
                        callBackListener.callBack("-1")
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        LCBaseUtil.showToast(mContext,"支付异常，为保证您的资金安全，请不要继续支付，联系客服处理！")
//                        PayDemoActivity.showAlert(this@PayDemoActivity, getString(R.string.pay_failed) + payResult)
                    }
                }

                else -> {}
            }
        }
    }

    /**
     *  @time 2025/8/8  13:58
     *  @author Im_jingwei
     *  @desc 验证支付宝支付结果
     */
    private fun verifyAliPay(orderNo: String) {
        showProgress("正在验证支付结果...")
        val httpUtil = OkHttpUtil()
        val jsonObject = JSONObject()
        jsonObject.put("orderNo", orderNo)
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_ALIPAY_QUERY
        httpUtil.httpRequest(url, token, jsonObject.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                LCBaseUtil.showToast(mContext, "支付宝订单验证失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    val jsonObject = JSONObject(response)
                    val code = jsonObject.getInt("code")
                    val data = jsonObject.getJSONObject("data")
                    if (code == 200) {
                        val state = data.getString("status")
                        if (state == "TRADE_SUCCESS") {
                            LCBaseUtil.showToast(mContext, "支付结果验证成功，你已经是VIP了！")
                        }
                    } else {
                        LCBaseUtil.showToast(mContext, "支付宝订单验证异常,请联系客服处理。")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "支付宝订单验证失败，" + e.message)
                }
            }
        })
    }

    /***************************  支付宝 end  *************************/

    /***************************  微信支付 start  *************************/
    /**
     *  @time 2024/5/7  11:29
     *  @desc 创建微信订单
     *  @param url
     */
    fun creatWxPay(paytype:String) {
        showProgress("正在创建支付订单...")
        val httpUtil = OkHttpUtil()
        val jsonObject = JSONObject()
        jsonObject.put("productId", paytype)
        val token = LCSPUtil[mContext, AppConfig.SP_ACCESS_TOKEN]
        val url = NetWorkConfig.NET_URL_ROOT + NetWorkConfig.NET_URL_WECHAT_CREATE
        httpUtil.httpRequest(url, token, jsonObject.toString(), object : LCInterface.LcCallBackListener {
            override fun onFailure(call: Call, e: IOException) {
                cancleProgress()
                LCBaseUtil.showToast(mContext, "微信支付创建订单失败，" + e.message)
            }

            @Throws(IOException::class)
            override fun onSuccess(call: Call, response: String) {
                try {
                    cancleProgress()
                    val jsonObject = JSONObject(response)
                    val code = jsonObject.getInt("code")
                    val order = jsonObject.getJSONObject("data")
                    val msg = jsonObject.getString("message")
                    if (code == 200) {
                        toWechatMent(order)
                    } else {
                        LCBaseUtil.showToast(mContext, "微信支付创建订单异常，$msg")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    LCBaseUtil.showToast(mContext, "微信支付创建订单失败，" + e.message)
                }
            }
        })
    }

    /**
     *  @time 2025/8/7  20:00
     *  @author Im_jingwei
     *  @desc 调用支付宝支付
     */
    fun toWechatMent(orderInfo: JSONObject) {
        paymentUtil.wechatPay(mContext, orderInfo)
    }


    /***************************  微信支付 end  *************************/





    fun showProgress(msg:String) {
        if (progressDialog == null) {
            progressDialog = LcProgressUtil(mContext)
        }
        progressDialog!!.setText(msg)
        progressDialog!!.show()
    }

    open fun cancleProgress() {
        if (progressDialog != null && progressDialog!!.isShow) {
            progressDialog!!.cancel()
        }
    }

    /**
     *  @time 2024/7/8  16:39
     *  @author Im_jingwei
     *  @desc 销毁
     */
    override fun dismiss() {
        //关闭软键盘
        setBackgroundAlpha(1.0f)
        super.dismiss()
    }

    //设置窗口颜色
    private fun setBackgroundAlpha(bgAlpha: Float) {
        val lp = (mContext as Activity).window.attributes
        (mContext as Activity).window.setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND, WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        lp.alpha = bgAlpha //0.0-1.0
        (mContext as Activity).window.attributes = lp
    }

}